import pdfplumber
import docx
import pandas as pd
import chardet
import requests
from ...config import Config


def extract_text_from_pdf(file):
    """从PDF文件中提取文本"""
    try:
        text = ""
        with pdfplumber.open(file) as pdf:
            for page in pdf.pages:
                page_text = page.extract_text()
                if page_text:
                    text += page_text + "\n"
        return text
    except Exception as e:
        print(f"Error extracting text from PDF file: {e}")
        return None

def extract_text_from_word(file):
    """从Word文件中提取文本"""
    try:
        doc = docx.Document(file)
        text = "\n".join([para.text for para in doc.paragraphs])
        return text
    except Exception as e:
        print(f"Error extracting text from Word file: {e}")
        return None

def extract_text_from_excel(file):
    """从Excel文件中提取文本"""
    try:
        text = ""
        xls = pd.ExcelFile(file)
        for sheet_name in xls.sheet_names:
            df = pd.read_excel(file, sheet_name=sheet_name)
            text += df.to_string(header=False, index=False) + "\n"
        return text
    except Exception as e:
        print(f"Error extracting text from Excel file: {e}")
        return None

def extract_text_from_text(file):
    """从文本文件中提取文本"""
    try:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']
        if not encoding:
            encoding = 'utf-8'
        text = raw_data.decode(encoding, errors='ignore')
        return text
    except Exception as e:
        print(f"Error reading text file: {e}")
        return None

def summarize_text_with_large_model(text):
    """使用大模型对文本进行总结"""
    API_ENDPOINT = Config.XIAOZHI_URL  # 替换为你的 API 端点
    prompt = (
        "请基于以下内容生成一篇博客或新闻文章的简洁总结。"
        "总结应包括：\n"
        "1. 标题和主要内容：简要描述文章的主题和核心信息。\n"
        "2. 重要细节：突出文章中的关键事实或数据。\n"
        "3. 背景和上下文：提供必要的背景信息，使读者理解文章的内容。\n"
        "4. 结论和观点：总结文章的主要观点或结论。\n\n"
        f"内容如下：\n{text}"
    )

    payload = {
        "model": "llama3",
        "messages": [{"role": "user", "content": prompt}]
    }

    try:
        response = requests.post(API_ENDPOINT, json=payload)
        response.raise_for_status()
        summary = response.json()
        return summary
    except requests.exceptions.RequestException as e:
        print(f"Error summarizing text with large model: {e}")
        return None

def fetch_document_text(file):
    """从上传的文件中提取文本内容"""
    if file.filename.endswith('.pdf'):
        return extract_text_from_pdf(file)
    elif file.filename.endswith('.docx'):
        return extract_text_from_word(file)
    elif file.filename.endswith('.xlsx'):
        return extract_text_from_excel(file)
    elif file.filename.endswith('.txt'):
        return extract_text_from_text(file)
    else:
        print("Unsupported file format")
        return None

def summarize_document(file):
    """总结文档内容"""
    text = fetch_document_text(file)
    if text:
        summary = summarize_text_with_large_model(text)
        return summary
    else:
        return None
